package com.demo.user.controller;


import com.demo.common.util.R;
import com.demo.user.entity.User;
import com.demo.user.exception.UserException;
import com.demo.user.service.UserService;
import com.fasterxml.jackson.annotation.JsonView;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 用户 controller
 *
 * @author YT
 * @date 2019-05-20
 */
@RestController
@AllArgsConstructor
@RequestMapping("/user")
@Slf4j
public class UserController {

    // Eureka客户端，可以获取到服务实例信息
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private UserService userService;

    @PostMapping("/getuser")
    public R getUser(@RequestBody User user) throws Exception {
        return new R<>(user);
    }

    @GetMapping("/getserver")
    public R getServer() {
        User user = new User();
        user.setName("yt");
        return new R<>(user);
    }

    @PostMapping("/saveUser")
    public R saveUser() {
        User user = new User();
        user.setName("user-service");
        userService.insertUserServiceName(user);
        return new R<>();
    }

    @PostMapping("/save")
    public R save(@RequestBody User user) {
        return new R<>(userService.saveOrUpdate(user));
    }

    /**
     * 选择展示试图为 UserBaseView
     *
     * @return
     */
    @JsonView(User.UserBaseView.class)
    @GetMapping("/testJsonView")
    public User testJsonView() {
        User user = new User();
        user.setId("1");
        user.setName("yt");
        return user;
    }

    /**
     * 选择展示试图为 UserDetalView
     *
     * @return
     */
    @JsonView(User.UserDetalView.class)
    @GetMapping("/testJsonViews")
    public R testJsonViews() {
        User user = new User();
        user.setId("1");
        user.setName("yt");
        return new R<>(user);
    }

    /**
     * 使用 @Valid 校验参数
     *
     * @param user
     * @return
     */
    @PostMapping("/addUser")
    public R addUser(@Valid @RequestBody User user, BindingResult bindingResult) {
        bindingResult.getAllErrors().stream().forEach(error -> {
            log.info(error.getDefaultMessage());
        });
        log.info(user.getName());
        return new R<>("success");
    }

    /**
     * 自定义异常处理返回信息
     *
     * @param user
     * @return
     */
    @PostMapping("/testException")
    public R testException(@Valid @RequestBody User user) throws UserException {
        throw new UserException();
    }


}
